<template>
  <!-- 发送邮箱验证码的弹框组件 -->
  <Dialog
    :show="dialogConfig.show"
    :title="dialogConfig.title"
    :buttons="dialogConfig.buttons"
    width="450px"
    :showCancel="false"
    @close="dialogConfig.show = false"
  >
    <el-form :model="formData" :rules="rules" ref="formDataRef" @submit.prevent>
      <el-form-item label="发送到邮箱：">{{ props.email }}</el-form-item>
      <!-- 这个里面的图片验证码是发送邮箱验证码前填的图片验证码，类型为1 -->
      <ImageCodeFormItem
        :formData="formData"
        :imageCodeType="1"
        ref="imageCodeFormItemRef"
      />
    </el-form>
  </Dialog>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

/* 获取图片验证码的表单项 */
import ImageCodeFormItem from "@/components/ImageCodeFormItem.vue";

/* 展示外部传递的邮箱 */
const props = defineProps({
  email: { type: String, default: "no email" },
  oprType: { type: Number, default: 0 },
});

const dialogConfig = reactive({
  show: false,
  title: "获取邮箱验证码",
  buttons: [
    {
      type: "primary",
      text: "发送验证码",
      click: (e) => {
        submitForm();
      },
    },
  ],
});

const formData = ref({});
const formDataRef = ref();
const rules = {
  imageCode: [{ required: true, message: "请输入图片验证码", trigger: "blur" }],
};

/* 发送邮箱验证码 */
const submitForm = async () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = {};
    Object.assign(params, formData.value);
    params.type = props.oprType; // 这里的type指定操作类型为注册/找回密码（登录不用获取邮箱验证码）
    params.email = props.email;
    let result = await proxy.Request({
      method: "post",
      url: proxy.Api.sendEmailCode,
      params,
    });
    if (!result) {
      // 失败要重新获取图片验证码
      imageCodeFormItemRef.value.changeImageCode();
      return;
    }
    proxy.Message.success("发送验证码成功，请注意查收");
    dialogConfig.show = false;
  });
};

const imageCodeFormItemRef = ref();

/* 外部调用show方法显示弹框 */
const show = () => {
  dialogConfig.show = true;
  // 清空表单数据，重新获取图片验证码
  formData.value = {};
  nextTick(() => {
    imageCodeFormItemRef.value.changeImageCode();
    formDataRef.value.resetFields();
  });
};
defineExpose({ show });
</script>

<style lang="scss" scoped>
</style>
